﻿using Inovout.Cloud.Applications.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Routing;
using System.Web.Routing;

namespace Inovout.Cloud.Web.Http
{
    public class HttpApplicationInterfaceRouteCollection : HttpRouteCollection
    {
        public HttpApplicationInterfaceRouteCollection(IEnumerable<HttpApplicationInterface> apis)
        {
            foreach (var api in apis)
            {
                HttpApplicationRoute httpAPIRoute = new HttpApplicationRoute(api);
                this.Add(httpAPIRoute);
            }
        }
        private readonly List<HttpApplicationRoute> _collection = new List<HttpApplicationRoute>();
        public void Add(HttpApplicationRoute httpApplicationRoute)
        {
            _collection.Add(httpApplicationRoute);
        }

        public IList<HttpApplicationInterface> GetApplicationInterfaces(HttpRequestMessage request)
        {
            IList<HttpApplicationInterface> listAPI = new List<HttpApplicationInterface>();
            for (int i = 0; i < _collection.Count; i++)
            {
                string virtualPathRoot = GetVirtualPathRoot(request.GetRequestContext());//GetVirtualPathRoot(request.GetRequestContext());
                if (_collection[i].Match(virtualPathRoot, request))
                {
                    listAPI.Add(_collection[i].HttpApplicationInterface);
                }
            }
            return listAPI;

        }

        public string GetVirtualPathRoot(HttpRequestContext requestContext)
        {
            string virtualPathRoot;
            if (requestContext != null)
            {
                virtualPathRoot = requestContext.VirtualPathRoot;
            }
            else
            {
                virtualPathRoot = String.Empty;
            }

            if (!virtualPathRoot.EndsWith("/", StringComparison.Ordinal))
            {
                virtualPathRoot += "/";
            }

            return virtualPathRoot;
        }

    }


}